<?php
/**
 * Import component
 * @package Db
 * @subpackage Db_Object
 * @author Kirill A Egorov kirill.a.egorov@gmail.com 
 * @copyright Copyright (C) 2011-2012  Kirill A Egorov, 
 * DVelum project http://code.google.com/p/dvelum/ , http://dvelum.net
 * @license General Public License version 3
 */
class Db_Object_Import {
	static private $_instance = null;
    protected function __construct(){}
    protected function __clone(){}
    /**
     * @return Db_Object_Builder
     */
    static public function getInstance(){
        if(is_null(self::$_instance))
            self::$_instance = new self();
            
        return self::$_instance;    
    }
    /**
     * @todo cleanup the code
     * @param Zend_Db_Adapter_Mysqli $dbAdapter
     * @param string $tableName
     * @param string $configName
     * @throws Exception
     * @return 
     */
    public function createConfigByTable(Zend_Db_Adapter_Mysqli $dbAdapter, $tableName, $configName) {
    	$confName = $configName . '.php';
    	$config = Store::factory(Store::Local)->get('config_main');
    	$confPath = $config->get('object_configs');
    	
    	//Включить проверку после завершения написания функции
//    	if (file_exists($confPath . $configName))
//    		return array('success' => false, 'error' => 'Поле "Имя конфига" должно быть уникальным');
    	
		if (Config_File_Array::create($confPath . $confName) === false)
    		throw new Exception(LANG_CANT_WRITE_FS);
    	
    	$newConfig = Config::factory(Config::File_Array, $confPath . $confName);
    	
    	$desc = $dbAdapter->describeTable($tableName);
    	$engine = $dbAdapter->fetchRow('SHOW TABLE STATUS from sitebuilder where `Name` = "'.$tableName.'"');
    	$indexes = $dbAdapter->fetchAll('SHOW INDEX FROM `' . $tableName . '`');
    	
    	$index = array();
    	$indexGroups = array();
    	foreach ($indexes as $k => $v) {
    		if (strtolower($v['Column_name']) == 'id')
    			continue;
    			
    		$flag = false;
    		if (!empty($index))
	    		foreach ($index as $k => &$val){
	    			if ($k == $v['Key_name']) {
	    				$val['columns'][] = $v['Column_name'];
	    				$flag = true;
	    				
	    				if (!$v['Non_unique'])
							$indexGroups[$v['Column_name']][] = $v['Key_name'];
	    				
	    				break;
	    			}    				
	    		}
	    		
    		unset($val);
    		if ($flag)
    			continue;
    		
    		if ($v['Index_type'] == 'FULLTEXT')
    			$index[$v['Key_name']]['fulltext'] = true;
    		else
    			$index[$v['Key_name']]['fulltext'] = false;
    			
    		/**
    		 * Non_unique 
			 *	0 if the index cannot contain duplicates, 1 if it can.
    		 */
    		if ($v['Non_unique'])
    			$index[$v['Key_name']]['unique'] = false;
    		else {
    			$index[$v['Key_name']]['unique'] = true;
    			$indexGroups[$v['Column_name']][] = $v['Key_name'];
    		}
    		
    		$index[$v['Key_name']]['columns'] = array(
    			$v['Column_name']
    		);
    	}
    	
    	$fields = array();
    	foreach ($desc as $k => $v) {
    		if (strtolower($v['COLUMN_NAME']) == 'id')
    			continue;
    			
    		$fields[$k] = array(
    							'name' => $v['COLUMN_NAME'],
			                    'title' => '',
			                    'db_type' => $v['DATA_TYPE']
    						);
    						
			if (!empty($v['LENGTH']))
				$fields[$k]['db_len'] = $v['LENGTH'];
				
			if ($v['DEFAULT'] !== null)
				$fields[$k]['db_default'] = $v['DEFAULT'];
				
			if ($v['NULLABLE'])
				$fields[$k]['db_isNull'] = true;
			else {
				$fields[$k]['db_isNull'] = false;
				$fields[$k]['required'] = true;
			}
				
			if ($v['UNSIGNED'])
				$fields[$k]['db_unsigned'] = true;
				
			if (!empty($v['SCALE']))
				$fields[$k]['db_scale'] = $v['SCALE'];
				
			if (!empty($v['PRECISION']))	
				$fields[$k]['db_precision'] = $v['PRECISION'];
				
			if (array_key_exists((string)$v['COLUMN_NAME'], $indexGroups))
				$fields[$k]['unique'] = $indexGroups[$v['COLUMN_NAME']];
				
			if ($v['IDENTITY'])
				$fields[$k]['auto_increment'] = true;
    	}
    	
    	$newConfig->set('table', $configName);
    	$newConfig->set('engine', $engine['Engine']);
    	$newConfig->set('rev_control', false);
    	$newConfig->set('link_title', '');
    	$newConfig->set('fields', $fields);
    	if (!empty($index))
    		$newConfig->set('indexes', $index);
    	
    	$newConfig->save();
    	
//    	$builder = Db_Object_Builder::getInstance();
//    	$builder->build(new Db_Object($configName));
    	
    	echo '<pre>'; print_r($newConfig); die();
    }
}